from flask import Flask, Response, request, Blueprint
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from sqlalchemy import and_

from app.model.CalculationModel import CalcuResult
from app.service.TransactionCharactersService import TransactionCharactersService
from app.service.transactionFeaturesService import TransactionFeatures
from app.common.commonMessage import CommonMassages
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

import json
app = Flask(__name__)
# 创建蓝图
transaction_characters_bp = Blueprint('transaction_character', __name__ , url_prefix='/kshx')

transactionCharactersService = TransactionCharactersService()
transactionFeatures = TransactionFeatures()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

@transaction_characters_bp.route('/transactionCharacters', methods=['GET'])
# @jwt_required()
def get_transaction_characters():
    companyName = request.args.get("companyName", type=str)
    company_type = request.args.get("company_type", type=int)
    year = request.args.get("year", type=int)
    # start_date = request.args.get("start_date", type=str)
    # end_date = request.args.get("end_date", type=str)
    # data1 = transactionCharactersService.select_trading_indicators_data(session, companyName, company_type, start_date, end_date)
    # data2 = transactionCharactersService.select_trading_statistics_data(session,companyName, company_type, start_date, end_date)
    # data = {
    #     'jyzb':data1, # 交易指标
    #     'jytj':data2 # 交易统计
    # }
    if int(company_type) in [2, 3]:
        result = session.query(CalcuResult.JSONDATA).filter(
            and_(
                CalcuResult.GSMC == companyName,
                CalcuResult.TYPE == 'tn',
                CalcuResult.JYND == year
            )
        ).scalar()
        data = json.loads(result)
    else:
        data = transactionFeatures.select_trading_indicators_data(session, companyName, company_type, year)
    if data is not None:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, cls=CustomJSONEncoder)
    # return Response(resp_data, content_type='application/json')
    return Response(resp_data)